<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/9/18
 * Time: 14:42
 */

namespace common\members\wodrow\widgets\ueditor;

use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

/**
 * Class Ueditor
 * @package common\members\wodrow\widgets\ueditor
 * rewrite for solve modal problem
 */
class Ueditor extends \crazydb\ueditor\UEditor
{
    /**
     * UEditor配置
     * @var array
     */
    public $config = [
        'zIndex' =>  "1100",
    ];

    /**
     * 输出widget页面，注册相关JS代码。
     */
    public function run()
    {
        $id = $this->hasModel() ? Html::getInputId($this->model, $this->attribute) : $this->id;
        if (!preg_match('/^[\w\d_]+$/', $this->name))
            $name = preg_replace('/[^\w\d_]/', '_', $this->name);
        else
            $name = $this->name;

        $config = Json::encode($this->config);

        //ready部分代码，是为了缩略图管理。UEditor本身就很大，在后台直接加载大文件图片会很卡。
        $script = <<<UEDITOR
        var {$name} = UE.getEditor('{$id}',{$config});
        {$name}.ready(function(){
            this.addListener( "beforeInsertImage", function ( type, imgObjs ) {
                for(var i=0;i < imgObjs.length;i++){
                    imgObjs[i].src = imgObjs[i].src.replace(".thumbnail","");
                }
            });
        });
        $('#ajaxCrudModal').on('hidden.bs.modal', function () {
            if(Object.keys({$name}).length === 0){}else{
                {$name}.destroy();
            }           
        });
UEDITOR;

        $this->getView()->registerJs($script);

        if ($this->hasModel())
            return Html::activeTextarea($this->model, $this->attribute);
        else
            return Html::textarea(ArrayHelper::getValue($this->config, 'textarea', $this->name), $this->value, ['id' => $id]);
    }
}